package org.example.aiservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.aiservice.feign.FileServiceClient;
import org.example.aiservice.mapper.ChatHistoryMapper;
import org.example.aiservice.pojo.ChatHistory;
import org.example.aiservice.service.AlibabaAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiChatController {

    @Autowired
    private AlibabaAiService alibabaAiService;

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;


    @Autowired
    private FileServiceClient fileServiceClient;

    @PostMapping("/chat")
    public Map<String, Object> chat(@RequestParam Long fileId, @RequestParam String question) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取文件内容
            String fileContent = getFileContent(fileId);
            
            // 调用AI服务
            String answer = alibabaAiService.chat(question, fileContent);
            
            // 保存对话记录
            ChatHistory chatHistory = new ChatHistory()
                    .setFileId(fileId)
                    .setQuestion(question)
                    .setAnswer(answer)
                    .setCreatedAt(LocalDateTime.now());
            chatHistoryMapper.insert(chatHistory);
            
            result.put("success", true);
            result.put("answer", answer);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "对话失败: " + e.getMessage());
        }
        return result;
    }

    @GetMapping("/history/{fileId}")
    public Map<String, Object> getChatHistory(@PathVariable Long fileId) {
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<ChatHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_id", fileId).orderByDesc("created_at");
            List<ChatHistory> historyList = chatHistoryMapper.selectList(queryWrapper);
            
            result.put("success", true);
            result.put("data", historyList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取历史记录失败: " + e.getMessage());
        }
        return result;
    }

    private String getFileContent(Long fileId) {
        try {
            // 通过Feign调用file-service获取文件内容
            return fileServiceClient.getFileContent(fileId);
        } catch (Exception e) {
            throw new RuntimeException("获取文件内容失败: " + e.getMessage());
        }
    }
}